<template>
  <view class="warehouse-container">
    <!-- 头部 -->
    <view class="header">
      <view class="header-content">
        <text class="title">装饰仓库</text>
        <text class="subtitle">管理您的装饰物品</text>
      </view>
    </view>

    <!-- 当前佩戴状态 -->
    <view class="current-wearing">
      <view class="section-title">
        <text class="title-text">当前佩戴</text>
      </view>
      <view class="wearing-grid">
        <view class="wearing-item" v-for="(item, type) in currentWearing" :key="type">
          <view class="item-icon">{{ getTypeIcon(type) }}</view>
          <text class="item-name">{{ item.name || '未佩戴' }}</text>
          <view v-if="item.id" class="item-preview">
            <image :src="item.imageUrl || '/static/images/default-item.png'" class="preview-image" />
          </view>
        </view>
      </view>
    </view>

    <!-- 分类导航 -->
    <view class="category-nav">
      <scroll-view scroll-x="true" class="nav-scroll">
        <view class="nav-items">
          <view 
            v-for="category in categories" 
            :key="category.value"
            class="nav-item"
            :class="{ active: selectedCategory === category.value }"
            @click="selectCategory(category.value)"
          >
            <text class="nav-text">{{ category.label }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 装饰物品列表 -->
    <view class="items-section">
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="filteredItems.length === 0" class="empty-container">
        <text class="empty-text">暂无{{ getCategoryName(selectedCategory) }}物品</text>
      </view>
      
      <view v-else class="items-grid">
        <view 
          v-for="item in filteredItems" 
          :key="item.id"
          class="item-card"
          :class="{ active: isItemActive(item) }"
          @click="showItemDetail(item)"
        >
          <view class="item-image-container">
            <image 
              :src="item.imageUrl || '/static/images/default-item.png'" 
              class="item-image"
              mode="aspectFill"
            />
            <view v-if="isItemActive(item)" class="active-badge">
              <text class="badge-text">使用中</text>
            </view>
            <view v-if="item.rarity" class="rarity-badge" :class="getRarityClass(item.rarity)">
              <text class="rarity-text">{{ getRarityText(item.rarity) }}</text>
            </view>
          </view>
          
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-description">{{ item.description }}</text>
            
            <view class="item-actions">
              <button 
                v-if="!isItemActive(item)"
                class="wear-button"
                @click.stop="wearItem(item)"
              >
                <text class="wear-text">佩戴</text>
              </button>
              <view v-else class="wearing-status">
                <text class="wearing-text">使用中</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 物品详情弹窗 -->
    <view v-if="showDetailModal" class="detail-modal" @click="closeDetailModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ selectedItem.name }}</text>
          <text class="close-btn" @click="closeDetailModal">×</text>
        </view>
        
        <view class="modal-body">
          <image 
            :src="selectedItem.imageUrl || '/static/images/default-item.png'" 
            class="detail-image"
            mode="aspectFit"
          />
          
          <view class="detail-info">
            <text class="detail-description">{{ selectedItem.description }}</text>
            
            <view class="detail-meta">
              <view class="meta-item">
                <text class="meta-label">类型：</text>
                <text class="meta-value">{{ getItemTypeName(selectedItem.itemType) }}</text>
              </view>
              <view class="meta-item">
                <text class="meta-label">稀有度：</text>
                <text class="meta-value">{{ getRarityText(selectedItem.rarity) }}</text>
              </view>
              <view class="meta-item">
                <text class="meta-label">获得方式：</text>
                <text class="meta-value">{{ getAcquisitionMethodName(selectedItem.acquisitionMethod) }}</text>
              </view>
              <view class="meta-item">
                <text class="meta-label">获得时间：</text>
                <text class="meta-value">{{ formatDate(selectedItem.acquiredAt) }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button 
            v-if="!isItemActive(selectedItem)"
            class="wear-button-modal"
            @click="wearItem(selectedItem)"
          >
            <text class="wear-text">佩戴此物品</text>
          </button>
          <view v-else class="wearing-status-modal">
            <text class="wearing-status-text">当前正在使用</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 佩戴确认弹窗 -->
    <view v-if="showWearModal" class="wear-modal" @click="closeWearModal">
      <view class="wear-content" @click.stop>
        <view class="wear-header">
          <text class="wear-title">确认佩戴</text>
        </view>
        
        <view class="wear-body">
          <view class="wear-item">
            <image :src="wearItem.imageUrl || '/static/images/default-item.png'" class="wear-image" />
            <view class="wear-info">
              <text class="wear-name">{{ wearItem.name }}</text>
              <text class="wear-type">{{ getItemTypeName(wearItem.itemType) }}</text>
            </view>
          </view>
          
          <view class="wear-notice">
            <text class="notice-text">佩戴后将替换当前使用的{{ getItemTypeName(wearItem.itemType) }}</text>
          </view>
        </view>
        
        <view class="wear-footer">
          <button class="cancel-button" @click="closeWearModal">
            <text class="cancel-text">取消</text>
          </button>
          <button class="confirm-button" @click="confirmWear">
            <text class="confirm-text">确认佩戴</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 加载提示 -->
    <view v-if="wearing" class="loading-overlay">
      <view class="loading-content">
        <text class="loading-text">佩戴中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { NETWORK_CONFIG } from '@/config/network.js'

export default {
  name: 'WarehousePage',
  data() {
    return {
      userId: null,
      loading: false,
      wearing: false,
      selectedCategory: 'ALL',
      ownedItems: [],
      currentWearing: {},
      showDetailModal: false,
      showWearModal: false,
      selectedItem: null,
      wearItem: null,
      categories: [
        { label: '全部', value: 'ALL' },
        { label: '主题', value: 'theme' },
        { label: '头像框', value: 'avatar_frame' },
        { label: '聊天气泡', value: 'chat_bubble' },
        { label: '铭牌', value: 'badge' },
        { label: '宠物', value: 'pet' },
        { label: '吉祥物', value: 'mascot' },
        { label: '个人名片', value: 'personal_card' },
        { label: '企业名片', value: 'enterprise_card' }
      ]
    }
  },
  computed: {
    filteredItems() {
      let items = this.ownedItems
      
      // 按分类筛选
      if (this.selectedCategory !== 'ALL') {
        items = items.filter(item => item.decoration_type === this.selectedCategory)
      }
      
      return items
    }
  },
  onLoad(options) {
    this.userId = options.userId || 1 // 默认用户ID，实际应该从登录状态获取
    this.loadUserDecorations()
    this.loadCurrentWearing()
  },
  methods: {
    // 加载用户装饰物品
    async loadUserDecorations() {
      this.loading = true
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/decoration/owned/${this.userId}`,
          method: 'GET',
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          this.ownedItems = response.data.data || []
        }
      } catch (error) {
        console.error('加载用户装饰物品失败:', error)
        uni.showToast({
          title: '加载装饰物品失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载当前佩戴的装饰
    async loadCurrentWearing() {
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/decoration/current/${this.userId}`,
          method: 'GET',
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          this.currentWearing = response.data.data || {}
        }
      } catch (error) {
        console.error('加载当前佩戴装饰失败:', error)
      }
    },
    
    // 选择分类
    selectCategory(category) {
      this.selectedCategory = category
    },
    
    // 显示物品详情
    showItemDetail(item) {
      this.selectedItem = item
      this.showDetailModal = true
    },
    
    // 关闭详情弹窗
    closeDetailModal() {
      this.showDetailModal = false
      this.selectedItem = null
    },
    
    // 佩戴物品
    wearItem(item) {
      this.wearItem = item
      this.showWearModal = true
    },
    
    // 关闭佩戴弹窗
    closeWearModal() {
      this.showWearModal = false
      this.wearItem = null
    },
    
    // 确认佩戴
    async confirmWear() {
      if (!this.wearItem) {
        return
      }
      
      this.wearing = true
      
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/decoration/wear`,
          method: 'POST',
          data: {
            userId: this.userId,
            decorationType: this.wearItem.decoration_type,
            sponsorItemId: this.wearItem.sponsor_item_id
          },
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          uni.showToast({
            title: '佩戴成功',
            icon: 'success'
          })
          
          // 更新当前佩戴状态
          this.loadCurrentWearing()
          
          // 关闭弹窗
          this.closeWearModal()
          this.closeDetailModal()
        } else {
          uni.showToast({
            title: response.data.message || '佩戴失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('佩戴失败:', error)
        uni.showToast({
          title: '佩戴失败',
          icon: 'none'
        })
      } finally {
        this.wearing = false
      }
    },
    
    // 检查物品是否正在使用
    isItemActive(item) {
      const currentItem = this.currentWearing[item.decoration_type]
      return currentItem && currentItem.sponsor_item_id === item.sponsor_item_id
    },
    
    // 获取类型图标
    getTypeIcon(type) {
      const iconMap = {
        'theme': '🎨',
        'avatar_frame': '🖼️',
        'chat_bubble': '💬',
        'badge': '🏆',
        'pet': '🐾',
        'mascot': '🎭',
        'personal_card': '👤',
        'enterprise_card': '🏢'
      }
      return iconMap[type.toLowerCase()] || '🎁'
    },
    
    // 获取分类名称
    getCategoryName(category) {
      const categoryMap = {
        'ALL': '装饰',
        'theme': '主题',
        'avatar_frame': '头像框',
        'chat_bubble': '聊天气泡',
        'badge': '铭牌',
        'pet': '宠物',
        'mascot': '吉祥物',
        'personal_card': '个人名片',
        'enterprise_card': '企业名片'
      }
      return categoryMap[category] || category
    },
    
    // 获取商品类型名称
    getItemTypeName(type) {
      const typeMap = {
        'theme': '主题',
        'avatar_frame': '头像框',
        'chat_bubble': '聊天气泡',
        'badge': '铭牌',
        'pet': '宠物',
        'mascot': '吉祥物',
        'personal_card': '个人名片',
        'enterprise_card': '企业名片'
      }
      return typeMap[type] || type
    },
    
    // 获取稀有度文本
    getRarityText(rarity) {
      const rarityMap = {
        'COMMON': '普通',
        'RARE': '稀有',
        'EPIC': '史诗',
        'LEGENDARY': '传说'
      }
      return rarityMap[rarity] || rarity
    },
    
    // 获取稀有度样式类
    getRarityClass(rarity) {
      const classMap = {
        'COMMON': 'rarity-common',
        'RARE': 'rarity-rare',
        'EPIC': 'rarity-epic',
        'LEGENDARY': 'rarity-legendary'
      }
      return classMap[rarity] || ''
    },
    
    // 获取获得方式名称
    getAcquisitionMethodName(method) {
      const methodMap = {
        'purchase': '购买',
        'gift': '赠送',
        'event': '活动',
        'default': '默认'
      }
      return methodMap[method] || method
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
  }
}
</script>

<style scoped>
.warehouse-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  color: white;
  text-align: center;
}

.title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  display: block;
  font-size: 24rpx;
  opacity: 0.8;
}

/* 当前佩戴样式 */
.current-wearing {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  margin-bottom: 20rpx;
}

.title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.wearing-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.wearing-item {
  text-align: center;
  padding: 20rpx 10rpx;
  background: #f8f9fa;
  border-radius: 15rpx;
}

.item-icon {
  font-size: 32rpx;
  margin-bottom: 10rpx;
}

.item-name {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.item-preview {
  width: 60rpx;
  height: 60rpx;
  margin: 0 auto;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

/* 分类导航样式 */
.category-nav {
  background: white;
  border-radius: 20rpx;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.nav-scroll {
  white-space: nowrap;
}

.nav-items {
  display: flex;
  padding: 0 20rpx;
}

.nav-item {
  padding: 15rpx 25rpx;
  margin-right: 15rpx;
  background: #f8f9fa;
  border-radius: 25rpx;
  transition: all 0.3s ease;
}

.nav-item.active {
  background: #667eea;
  color: white;
}

.nav-text {
  font-size: 26rpx;
  white-space: nowrap;
}

/* 物品列表样式 */
.items-section {
  background: white;
  border-radius: 20rpx;
  padding: 20rpx;
}

.loading-container, .empty-container {
  text-align: center;
  padding: 60rpx 0;
}

.loading-text, .empty-text {
  color: #999;
  font-size: 28rpx;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.item-card {
  background: #f8f9fa;
  border-radius: 15rpx;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;
}

.item-card.active {
  border-color: #667eea;
  background: #f0f2ff;
}

.item-card:active {
  transform: scale(0.98);
}

.item-image-container {
  position: relative;
  height: 200rpx;
}

.item-image {
  width: 100%;
  height: 100%;
}

.active-badge {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background: #27ae60;
  color: white;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
}

.rarity-badge {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
}

.rarity-common {
  background: #95a5a6;
  color: white;
}

.rarity-rare {
  background: #3498db;
  color: white;
}

.rarity-epic {
  background: #9b59b6;
  color: white;
}

.rarity-legendary {
  background: #f39c12;
  color: white;
}

.item-info {
  padding: 20rpx;
}

.item-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-description {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-actions {
  display: flex;
  justify-content: center;
}

.wear-button {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.wearing-status {
  background: #27ae60;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

/* 详情弹窗样式 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  width: 90%;
  max-height: 80%;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.detail-image {
  width: 100%;
  height: 300rpx;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
}

.detail-info {
  margin-bottom: 20rpx;
}

.detail-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 10rpx;
}

.meta-value {
  font-size: 26rpx;
  color: #333;
}

.modal-footer {
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.wear-button-modal {
  width: 100%;
  height: 80rpx;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
}

.wearing-status-modal {
  text-align: center;
  padding: 20rpx;
}

.wearing-status-text {
  color: #27ae60;
  font-size: 28rpx;
}

/* 佩戴确认弹窗样式 */
.wear-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.wear-content {
  background: white;
  border-radius: 20rpx;
  width: 90%;
  max-width: 500rpx;
}

.wear-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.wear-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.wear-body {
  padding: 30rpx;
}

.wear-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.wear-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 15rpx;
  margin-right: 20rpx;
}

.wear-info {
  flex: 1;
}

.wear-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.wear-type {
  font-size: 24rpx;
  color: #666;
}

.wear-notice {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 15rpx;
}

.notice-text {
  font-size: 26rpx;
  color: #666;
}

.wear-footer {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.cancel-button, .confirm-button {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.cancel-button {
  background: #f8f9fa;
  color: #666;
}

.confirm-button {
  background: #667eea;
  color: white;
}

/* 加载样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10001;
}

.loading-content {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #333;
}
</style>
